package com.csii.activiti.server.core.engine.impl;

import cn.hutool.core.collection.CollUtil;
import com.csii.activiti.server.core.constant.CommonConstant;
import com.csii.activiti.server.core.engine.EngineService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ActivitiOptimisticLockingException;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class EngineServiceImpl implements EngineService {

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private HistoryService historyService;

    @Override
    public void complete(String taskId) {
        try{
            taskService.complete(taskId);
        }catch (ActivitiOptimisticLockingException exception){
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            taskService.complete(taskId);
        }
    }

    @Override
    public void deleteProcessInstance(String processInstanceId, String deleteReason) {
        try{
            runtimeService.deleteProcessInstance(processInstanceId, deleteReason);
        }catch (ActivitiOptimisticLockingException exception){
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runtimeService.deleteProcessInstance(processInstanceId, deleteReason);
        }
    }

    @Override
    public Map<String, Object> getFormDataByProcessInstanceId(String processInstanceId) {
        List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstanceId).list();
        if (CollUtil.isNotEmpty(list)){
            return list.stream().filter(item->item.getVariableName().startsWith(CommonConstant.NEW_FORM_DATA)).collect(Collectors.toMap(HistoricVariableInstance::getVariableName,HistoricVariableInstance::getValue,(v1,v2)->v2));
        }
        return null;
    }
}
